package com.douyin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyin.entity.*;
import com.douyin.mapper.RoleMapper;
import com.douyin.service.PermissionService;
import com.douyin.service.RolePermissionService;
import com.douyin.service.RoleService;
import com.douyin.service.UserRoleService;
import com.douyin.utils.R;
import com.douyin.vo.AssignRoleVO;
import com.douyin.vo.AuthorityVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private PermissionService permissionService;
    @Override
    public List<Tree> tree() {
        List<Tree> trees = permissionService.list((Wrapper<Permission>) null).stream().map(permission -> {

            Tree tree = new Tree();
            BeanUtils.copyProperties(permission, tree);
            tree.setTitle(permission.getName());
            tree.setSpread(true);
            return tree;
        }).collect(Collectors.toList());


        // 找到根节点
        List<Tree> parent = trees.stream().filter(tree -> tree.getPId().compareTo(0L) == 0).collect(Collectors.toList());
        for (Tree item : parent) {
            item.setChildren(new ArrayList<Tree>());
            item.getChildren().add(findChildren(item,trees));
        }

        return parent;
    }

    @Override
    @Transactional
    public R removeRole(String id) {
       try{
           //删除用户角色表
           userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId,id));
           //删除角色权限表
           rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId,id));
           //删除角色表
           this.removeById(id);
       }catch (Exception e){
           TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
           return R.error().message("删除失败");
       }
       return R.ok().message("删除成功");
    }

    @Override
    @Transactional
    public R gavePermission(AuthorityVO authorityVO) {
        try{
            //先删除该角色的所有权限
            rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId,authorityVO.getRid()));
            //授予权限
            List<RolePermission> rolePermissionList = new ArrayList<>();
            Integer rId = authorityVO.getRid();
            for (Integer pid : authorityVO.getPid()){
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(rId);
                rolePermission.setPermissionId(pid);
                rolePermissionList.add(rolePermission);
            }
            rolePermissionService.saveBatch(rolePermissionList);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("分配权限失败");
        }
        return R.ok().message("分配权限成功");
    }

    @Override
    @Transactional
    public R gaveRole(AssignRoleVO assignRoleVO) {
        try{
            Long userId = assignRoleVO.getUId();
            //先删除该用户的所有角色
            userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId,userId));
            //授予角色
            List<UserRole> userRoleList = new ArrayList<>();
            for (Long roleId : assignRoleVO.getRId()){
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoleList.add(userRole);
            }
            userRoleService.saveBatch(userRoleList);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("分配角色失败");
        }
        return R.ok().message("分配角色成功");
    }
    private Tree findChildren(Tree datum, List<Tree> trees) {
        datum.setChildren(new ArrayList<Tree>());
        for (Tree tree : trees) {
            if (tree.getPId().compareTo(datum.getId()) == 0) {
                datum.getChildren().add(findChildren(tree,trees));
            }
        }
        return datum;
    }
}
